/**
 * @author smayo
 */

var api_key = "ba2bb6c9967539014cf4216d58e34f44";
var proxy_url = "proxy.php";
var eventXML;
var prefs;

	

/*_IG_RegisterOnloadHandler(prefsReady);*/

$(document).ready(function()
	{
		
		

		initMap();
		initEdit();
		initSave();
		
		
		
		$("#tablist li").hover(
			function () {
				$(this).addClass("active");
			}, 
			function () {
				if ($(this).hasClass('selectable')) {
					$(this).removeClass("active");
				}
			}
		);
		
		$("#pagination_next").click(
			function(){
				$(this).fadeOut();
				$("#list1").fadeOut('slow', function(){
					$("#list2").fadeIn('slow');
					$("#pagination_back").fadeIn();
				});
				
		});
		$("#pagination_back").click(
			function(){
				$(this).fadeOut();
				$("#list2").fadeOut('slow', function(){
					$("#list1").fadeIn('slow');
					$("#pagination_next").fadeIn();
				});
				
		});
		
	}	
);

function prefsReady()
{
	
	prefs = new _IG_Prefs();
	var location = prefs.getString("location");
	//console.log("pref: " + location);
	if(location == ''){
		$('#location').val("London");
	}else{
		$('#location').val(location);
	}
	
	getEvents($('#location').val());

}

function initMap()
{
	$('#map').jmap('init', {mapCenter:[51.500152,-0.126236]});

}

function showMap(x,y)
{
	
	//hide list
	$("#list_container").fadeOut('slow');
	//show back button
	$('#map_back_btn').fadeIn();
	//showmap
	$("#map").fadeIn('normal', function(){
		$('#map').jmap('forceResizeEvent', {});
		$('#map').jmap('moveTo', {mapCenter: [x,y]});
	});
	$("#map_back_btn").click(hideMap);
	


}

function hideMap()
{
	$("#list_container").fadeIn();
	$("#map").fadeOut('slow');
	$('#map_back_btn').fadeOut('slow');
}

function getEvents(location)
{
	//alert(location);
	//http://ws.audioscrobbler.com/2.0/?method=geo.getevents&api_key=b25b959554ed76058ac220b7b2e0a026
	//var location = $('#location').text();
	var stat_option = "geo.getevents";
	var rest_url = "http://ws.audioscrobbler.com/2.0/?method=" + stat_option + "&location=" +location+ "&api_key=" + api_key;
	//construct GET request
	//alert(rest_url);
	//$.get(proxy_url, {url:rest_url}, handleEventResult);
	
	_IG_FetchXmlContent(rest_url, handleEventResult, { refreshInterval: 0 });

	
}

function handleEventResult(xml)
{
	var status = $(xml).find('lfm').attr('status');
	//console.log(xml);
	//alert(status);
	switch(status)
	{
		case "ok":
		{
			processEventResult(xml);
			break;
		}
		default:
		{
			displayError();
			break;
		}
	}
}

function processEventResult(xml)
{
	
	
	//$('#content_container').hide('slow');
//console.log(xml);

	eventXML = xml;
	var mainNode = $("event", xml);
	var tempDate;
	var eventDate;
	//alert(mainNode.length);
	$('#list1').html("");
	$('#list2').html("");
	$(mainNode).each(function(intIndex)
	{
		var listIndex = (intIndex <5)? '1' : '2';
		
		eventDate = $(this).children('startDate').text();
		if(tempDate != eventDate)
		{
			$('#list'+listIndex).append("<p class='subtext date'>"+eventDate+"</p>");
			tempDate = eventDate;
		}
		else if(intIndex ==5)
		{
			$('#list'+listIndex).append("<p class='subtext date'>"+eventDate+"</p>");
		}
		var title = $(this).children('title').text();
		//alert(title);
		var city = $(this).children('venue').children('location').children('city').text();
		var venue = $(this).children('venue').children('name').text();
		var point = $(this).children('venue').children('location').children('geo\\:point');
		//console.log(point);
		
		var lat = $(point).children('geo\\:lat').text();
		var lng = $(point).children('geo\\:long').text();
		//console.log(lat + ", " + lng);
		var id = $(this).children('id').text();
		var more_button = "<div class='element_button info' lat='"+lat+"' lng='"+lng+"' eid='"+id+"'>More Info</div>";
		//var buy_button = "<div class='element_button buy' lat='"+lat+"' lng='"+lng+"' eid='"+id+"'>Buy Tickets</div>";
		var map_button = "<div class='element_button map' lat='"+lat+"' lng='"+lng+"' eid='"+id+"'>Map</div>";
		
		$('#list'+listIndex).append("\n\t<li class='list_element' eid='"+id+"'><div class='element_info'><span class='bold'>"+title+"</span><br /><span class='subtext'>" +venue+", " + city + "</span></div><div style='min-width:300px'>" + map_button + more_button + "</div></li>");
		//alert($('#list'+listIndex).html());
	}); 
	$('.map').click(function(){
		var eventId = $(this).attr('eid');
		//find event in original xml responce by using the event id
		var eventNode = $(eventXML).filter('event id').find(":contains('"+eventId+"')");
		var title = $(eventNode).children('title').text();
		var venue = $(eventNode).children('venue').children('name').text();
		var location = $(eventNode).children('venue').children('location').children('street').text() + "<br />" + $(eventNode).children('venue').children('location').children('city').text() + "<br />" + $(eventNode).children('venue').children('location').children('postcode').text();
		var get_directions = "<a target='_blank' href='http://maps.google.com/maps?q=" + $(eventNode).children('venue').children('location').children('street').text() + " " + $(eventNode).children('venue').children('location').children('city').text() + " " + $(eventNode).children('venue').children('location').children('postcode').text()+"'>get directions</a>";
		var infoHtml = title + "<br />" + venue + "<br />" + location + "<br />" + get_directions;

		$('#map').jmap('addMarker', {pointLatLng:[$(this).attr("lat"), $(this).attr("lng")], pointHTML: eventDate + '<br /> '+infoHtml});
		

		showMap($(this).attr("lat"), $(this).attr("lng"));
	});
	$(".element_info").click(
			function(){
				$(this).parent().children("div.map").trigger("click");
	});
	$('.list_element').hover(
		function () {
			$(this).addClass("hover");
		}, 
		function () {
			$(this).removeClass("hover");
		}
	);
	
	
		
		
	$('.buy').click(function(){
	/*See Tickets search url
	 * artist uppercase '+' for spaces
	 * http://www.seetickets.com/see/event.asp?e|artist=THE+ARTIST+NAME
	 */
		var eventId = $(this).attr('eid');
		//find event in original xml responce by using the event id
		var eventNode = $(eventXML).filter('event id').find(":contains('"+eventId+"')");
		var artistName = $(eventNode).children('title').text().toUpperCase();
		artistName = artistName.replace(" ", "+");
		//window.location.href="http://www.seetickets.com/see/event.asp?e|artist=" + artistName;
		window.open("http://www.seetickets.com/see/event.asp?e|artist=" + artistName)
	});
	
	$(".info").click(function(){
		var eventId = $(this).attr('eid');
		//find event in original xml responce by using the event id
		var eventNode = $(eventXML).filter('event id').find(":contains('"+eventId+"')");
		var eventPage = $(eventNode).children('url').text();
		window.open(eventPage);
	});
	
	$(window).trigger("resize");
	

}

function updateStats()
{
	//get user id and stat option and send REST req to last.fm
	var user_id = "mayinhosa" /*$('#user').html()*/;
	var stat_option = "user.getweeklytrackchart";
	var rest_url = "http://ws.audioscrobbler.com/2.0/?method=" + stat_option + "&user=" +user_id+ "&api_key=" + api_key;
	//construct GET request
	$.get(proxy_url, {url:rest_url}, handleResult);
}



function handleResult(xml)
{
	//check status ok from return
	
	var status = $(xml).filter('lfm').attr('status');
	alert(status);
	switch(status)
	{
		case "ok":
		{
			processResult(xml);
			break;
		}
		default:
		{
			displayError();
			break;
		}
	}



}

function processResult(xml)
{
	alert("pr:" + $(xml).children('track').length);
	var mainNode = $(xml).filter('lfm').children();
	//alert(mainNode);
	$(mainNode).each(function()
	{
	    alert("pr1:" + $(this).children("artist").text());
	}); 
	
}

function displayError()
{
	$("#error").show('slow');
	$("#error").queue(function () {
		$("#error").animate({left:'-=0'},4000);
        $("#error").slideUp('slow');
        $(this).dequeue();
      });
	
	
	
}

function searchLocation()
{

	$('#map').jmap("searchAddress", {
		address: $('#location').text()
		},
		function(options, point) {
		//$('#map').jmap('addMarker', {pointLatLng:[point.y, point.x], pointHTML: 'Address' + options.address + ''});	
		$('#map').jmap('moveTo', {mapCenter: [point.y,point.x], centerMethod: 'pan'});
		alert(point.y+" "+point.x);
	});

	
}

function initEdit()
{
	$("#edit_id").click(
		function(e){
			var $old_location = $('#location').html();
			$('#top_container #search').html("location: <input id='location' name='location' type='text' value='" + $old_location + "' />  <button id=\"save_id\">save</button>");
			initSave();
		}
	);
}
function initSave()
{
	$("#location").focus(
		function(){
			$(this).select();		
		
	});
	$("#search").click(
		function(e){
			var new_location = $('#location').val();
			getEvents(new_location);
			//set prefs
			prefs.set("location", new_location);
			var location = prefs.getString("location");
			//console.log("pref: " + location);
			hideMap();
		}
	);
}


$(window).bind('resize', function() {	
	if(!jQuery.browser["msie"])
 	{
		var width = document.documentElement.clientWidth - 150;
		if (width > 120) {
			$('.element_info').width(width);
		}
	}
});


